package org.springframework.mock.web;

import com.xxxx.springMVC.day16.MyRequestMappingHandlerAdapter;
import com.xxxx.springMVC.day16.WebConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class D16 {

    public static void main(String[] args) throws Exception {
        AnnotationConfigServletWebServerApplicationContext context
                = new AnnotationConfigServletWebServerApplicationContext(WebConfig.class);
        // 解析 @RequestMapping 以及派生注解, 生成路径与控制器方法的映射关系,在初始化就生成
        RequestMappingHandlerMapping handlerMapping = context.getBean(RequestMappingHandlerMapping.class);
        // 获取映射结果
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
        handlerMethods.forEach((k,v) -> {
            System.out.println(k + "=" + v);
        });

        // 请求来了,获取控制器方法  返回处理器执行链对象
        MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test4");
        request.addHeader("token","这是令牌");
        request.setParameter("name","zs");
        MockHttpServletResponse response = new MockHttpServletResponse();
        HandlerExecutionChain chain = handlerMapping.getHandler(request);
        System.out.println(chain);

        System.out.println(">>>>>>>>>>>>>>>>>>>>");
        MyRequestMappingHandlerAdapter handlerAdapter = context.getBean(MyRequestMappingHandlerAdapter.class);
        handlerAdapter.invokeHandlerMethod(request,response,(HandlerMethod) chain.getHandler());

        // 检查响应
        byte[] content = response.getContentAsByteArray();
        System.out.println(new String(content, StandardCharsets.UTF_8));
        // System.out.println(">>>>>>>>>>>>>>>> 所有参数解析器");
        // for (HandlerMethodArgumentResolver resolver : handlerAdapter.getArgumentResolvers()) {
        //     System.out.println(resolver);
        // }
        //
        // System.out.println(">>>>>>>>>>>>>>>>>>> 所有返回值解析器");
        // for (HandlerMethodReturnValueHandler handler : handlerAdapter.getReturnValueHandlers()) {
        //     System.out.println(handler);
        // }
    }
}
